<template>
  <div>
    <div class="reg_box1">
      <img src="@/assets/img/bg_1@2x.png" alt="" />
      <div class="reg_box1_title">待支付</div>
      <div class="time" v-if="detail.createTime">
        请在{{ countdowntime }}内完成支付，超时将自动取消
      </div>
    </div>
    <div class="reg_box2">
      <div class="title_box"><span class="dot"></span>就诊人信息</div>
      <div class="info_box">
        <div class="left">就诊人：</div>
        <div class="right">
          {{ detail.name }}
          {{ " " + detail.sex == 1 ? "男" : "女" }}
          <!-- 1男 2女 -->
        </div>
      </div>
      <div class="info_box">
        <div class="left">证件号：</div>
        <div class="right">{{ detail.idNo }}</div>
      </div>
      <div class="info_box">
        <div class="left">手机号：</div>
        <div class="right">{{ detail.operMobile }}</div>
      </div>
      <div class="title_box"><span class="dot"></span>预约信息</div>
      <div class="info_box">
        <div class="left">医院：</div>
        <div class="right">中国医科大学附属口腔医院({{detail.hospitalName}})</div>
      </div>
      <div class="info_box">
        <div class="left">医院地址：</div>
        <div class="right">{{ detail.hospSeeDoctAddr }}</div>
      </div>
      <div class="info_box">
        <div class="left">预约科室：</div>
        <div class="right">{{ detail.deptName }}</div>
      </div>
      <div class="info_box">
        <div class="left">诊室：</div>
        <div class="right">{{ detail.roomName }}</div>
      </div>
      <div class="info_box">
        <div class="left">医生姓名：</div>
        <div class="right">{{ detail.doctorName }}</div>
      </div>
      <div class="info_box">
        <div class="left">就诊时间：</div>
        <div class="right">
          {{ detail.regDate + " " + detail.hospGetregDate }}

        </div>
      </div>
      <div class="info_box">
        <div class="left">门 诊 号 ：</div>
        <div class="right">{{ detail.hospPatientId }}</div>
      </div>
      <div class="info_box">
        <div class="left">挂号方式：</div>
        <div class="right">智慧医院</div>
      </div>
      <div class="title_box"><span class="dot"></span>订单信息</div>
      <div class="info_box">
        <div class="left">订单编号：</div>
        <div class="right">{{ detail.payOrderId }}</div>
      </div>
      <div class="info_box">
        <div class="left">下单时间：</div>
        <div class="right">{{ detail.createTime }}</div>
      </div>
      <div class="info_box">
        <div class="left">应付金额：</div>
        <div class="right">
          ￥{{ detail.totalFee / 100 }}
<!--          （挂号费￥0 检查费￥{{-->
<!--              detail.treatFee / 100-->
<!--          }}）-->
        </div>
      </div>
    </div>
    <div style="height: 20px"></div>
    <div class="btn_box">
      <div class="btn_box_1" @click="CancelRegLock">取消挂号</div>
      <div class="btn_box_2" @click="goPayment">
        支付 ￥{{ detail.totalFee / 100 }}
      </div>
    </div>
  </div>
</template>
<script>
import { getOrderRegDetail, cancelReg, payCreate, queryOrderStatus } from "@/api/api";

export default {
  data() {
    return {
      info: {},
      detail: {},
      userInfo: {},
      countdowntime: "",
      timer: null,
      count: 0,
    };
  },
  created() {
    this.info = this.$route.query;
    if (window.localStorage.getItem("userInfo")) {
      this.userInfo = JSON.parse(window.localStorage.getItem("userInfo"));
    } else {
      this.userInfo = JSON.parse(
        window.localStorage.getItem("defaultUserInfo")
      );
    }
    this.getOrderRegDetail();
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    getOrderRegDetail() {
      var data = {
        orderId: this.info.orderId,
      };
      getOrderRegDetail(data).then((res) => {
        if (res.code == 200) {
          this.detail = res.data;
          this.countdown(res.data.createTime);
        }
      });
    },
    CancelRegLock() {
      const that = this;
      const data = {
        hosId: "",
        orderId: this.info.orderId,
        hospPatientId: this.userInfo.hospPatientId,
        cancelRemark: "用户主动取消",
      };
      that.$vux.confirm.show({
        // 组件除show外的属性
        title: "提示",
        content: "是否确认取消挂号?",
        onCancel() { },
        onConfirm() {
          cancelReg(data).then((res) => {
            if (res.code == 200) {
              that.$vux.toast.show("取消挂号成功");
              setTimeout(() => {
                that.$router.go(-1)

              }, 1000);
            } else {
              that.$vux.toast.show(res.message);
            }

          });
        },
      });
    },
    // 去支付
    goPayment() {
      const that = this;
      that.payCreate(that.info.orderId);
      // this.$router.push({ path: "/payment", query: paydata });
    },
    // 获取微信支付配置
    payCreate(hospOrderId) {
      const that = this;
      payCreate({
        orderType: "1",
        orderId: hospOrderId,
        openId: window.localStorage.getItem("openId"),
      }).then((res) => {
        if (res.code == 200) {
          // 调起微信支付
          that.wxPay(res.data);
          window.localStorage.setItem("PAY_ORDER_ID", hospOrderId);
        } else {
          window.localStorage.setItem("PAY_ORDER_ID", "");
          alert(res.message);
        }
      });
    },
    // 发起微信支付
    wxPay(data, hospOrderId) {
      const that = this;
      that.pactname = "智慧医院"
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: data.appId, //公众号名称，由商户传入
          timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: data.nonceStr, //随机串
          package: data.package,
          signType: data.signType, //微信签名方式：
          paySign: data.paySign, //微信签名
        },
        function (response) {
          //TODO 应该再进行一次查单验证来保证支付成功
          if (response.err_msg == "get_brand_wcpay_request:ok") {

            // 使用以上方式判断前端返回,微信团队郑重提示：
            // res.err_msg将在用户支付成功后返回get_brand_wcpay_request:ok，但并不保证它绝对可靠。
            // setTimeout(() => {
            //   that.$router.replace({ path: "/registration_record_appo", query: that.info }
            //   );
            // }, 1000);
            that.$vux.loading.show()
            that.queryOrderStatusFun(hospOrderId)
            // window.location.href = "http://ydkq.eaccessy.com/registration_record";
          } else {
            window.localStorage.setItem("PAY_ORDER_ID", "");
            that.$vux.toast.show("支付失败");
            // alert("支付失败");
            // this.$router.go(-1)
            // that.$router.push("/registration_record");
          }
        }
      );
    },
    queryOrderStatusFun(orderId) {
      queryOrderStatus({
        orderId, //订单号
        "orderType": "1" //1:挂号 2:缴费
      }).then(res => {
        this.count++
        // 轮询6次
        if (this.count < 6) {
          if (res.code == 200) {
            this.$vux.loading.hide()
            alert("挂号成功")
            this.$router.push({
              path: "/registration_record_appo",
              query: {
                orderId,
                pactname: "智慧医院"
              },
            });
            return
          } else if (res.code == 400) {
            if (res.message == 'NOTIFY_HIS_ERROR') {
              alert("通知his失败");
              this.$vux.loading.hide()
              this.count = 0
              return
            } else {
              setTimeout(() => {
                this.queryOrderStatusFun(orderId)
              }, 2000)
            }

          }
        } else {
          alert("通知his失败");
          this.$vux.loading.hide()
          this.count = 0
          return
        }

      })
    },
    countdown(orderDate) {
      //orderDate是订单生效时间，后台的Date类型传到前端成了毫秒
      const that = this;
      var time = orderDate.replace(/-/g, "/");
      console.log(time);
      var now = new Date().getTime();
      var end = new Date(Date.parse(time) + 30 * 60 * 1000).getTime(); //提交订单的时间+30min就是订单失效时间，后台Date传过来变成了毫秒
      console.log(now);
      console.log(end);
      /*两个时间相减,得到的是毫秒ms,变成秒*/
      var result = Math.floor(end - now) / 1000; //result= 30*60s;
      this.timer = setInterval(sub, 1000); //定时器 调度对象
      console.log(result);

      /*封装减1秒的函数*/
      function sub() {
        if (result > 1) {
          result = result - 1;
          var second = Math.floor(result % 60); // 计算秒 ，取余
          var minite = Math.floor((result / 60) % 60); //计算分 ，换算有多少分，取余，余出多少秒
          //var hour = Math.floor(result/1000/60/60%24);  //计算小时，这里最长只有30min，用不着
          //var day = Math.floor(result/1000/60/60/24);   //计算天，这里最长只有30min，用不着
          that.countdowntime = minite + "分" + second + "秒";
        } else {
          //这里可以添加倒计时结束后需要执行的事件
          alert("未在规定时间内支付，订单已失效！");
          window.clearInterval(timer);
          //TODO 订单失效后的一些列操作：更改订单状态的同时回库存
        }
      }
    },
  },
  filters: {
    timefun(time) {
      if (time) {
        var newTime = time.slice(0, 2) + ":" + time.slice(2);
        newTime =
          newTime.slice(0, newTime.length - 2) +
          ":" +
          newTime.slice(newTime.length - 2);
        return newTime;
      }
    },
  },
};
</script>
<style scoped>
.reg_box1 {
  width: 100%;
  height: 142px;
  position: relative;
  color: #fff;
}

.reg_box1>div {
  position: relative;
  margin-left: 16px;
}

.reg_box1 .reg_box1_title {
  width: 80%;
  text-align: left;
  font-size: 17px;
  font-weight: bold;
  color: #ffffff;
  line-height: 42px;
}

.reg_box1 .time {
  font-size: 14px;
  /* font-weight: bold; */
  color: #ffffff;
  line-height: 42px;
}

.reg_box1 img {
  width: 100%;
  height: 100%;
  position: absolute;
}

.reg_box2 {
  width: calc(100% - 64px);
  padding: 16px;
  margin: 0px auto;
  position: relative;
  top: -55px;
  background: #ffffff;
  box-shadow: 0px 0px 10px 0px rgba(7, 62, 145, 0.24);
  border-radius: 5px;
}

.reg_box2 .title_box {
  display: flex;
  align-items: center;
  font-size: 17px;
  font-family: PingFang SC;
  font-weight: bold;
  color: #131a2a;
  line-height: 42px;
}

.reg_box2 .title_box .dot {
  width: 3px;
  height: 15px;
  background: #448eff;
  border-radius: 2px;
  margin-right: 12px;
}

.reg_box2 .info_box {
  display: flex;
  line-height: 26px;
  margin: 5px 0;
}

.reg_box2 .info_box .left {
  width: 80px;
  color: #a4adbe;
  font-size: 14px;
  text-align-last: justify;
}

.reg_box2 .info_box .right {
  width: calc(100% - 80px);
  word-wrap: break-word;
  word-break: normal;
  font-size: 15px;
}

.btn_box {
  height: 55px;
  width: 100%;

  display: flex;
  position: fixed;
  bottom: 0;

  background: #ffffff;
  box-shadow: 0px 0px 13px 0px rgba(181, 189, 197, 0.28);
}

.btn_box>div {
  width: 50%;
  height: 100%;
  line-height: 55px;
  font-size: 18px;
  text-align: center;
  font-weight: bold;
}

.btn_box .btn_box_1 {
  color: #448eff;
}

.btn_box .btn_box_2 {
  background: linear-gradient(90deg, #448eff 0%, #66a3ff 100%);
  color: #fff;
}
</style>
